package es.indra.malaga.filters;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;

import javax.faces.FactoryFinder;
import javax.faces.application.ResourceHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.richfaces.resource.ResourceHandlerImpl;

import es.indra.malaga.managedBeans.LoginBean;
import es.indra.malaga.viewBeans.UsuarioView;

public class FacesRedirectFilter implements Filter {

	private final static String EXTENSION = "faces";

	private HashMap<String, HashSet<String>> mapaPermisos = new HashMap<String, HashSet<String>>() {
		{
			put("admin", new HashSet<String>() {
				{
					add("/gestorEscolar/access/login.xhtml");
					add("/gestorEscolar/view/asignaturas/altaAsignatura.xhtml");
					add("/gestorEscolar/view/asignaturas/EditarAsignatura.xhtml");
					add("/gestorEscolar/view/asignaturas/ListadoAsignaturas.xhtml");
					add("/gestorEscolar/view/management/adminIndex.xhtml");
					add("/gestorEscolar/view/navigation/menuBar.xhtml");
					add("/gestorEscolar/view/profesores/AltaProfesor.xhtml");
					add("/gestorEscolar/view/profesores/AltaProfesorForm.xhtml");
					add("/gestorEscolar/view/profesores/EditarProfesores.xhtml");
					add("/gestorEscolar/view/profesores/ListadoProfesores.xhtml");
					add("/gestorEscolar/view/usuarios/AltaUsuario.xhtml");
					add("/gestorEscolar/view/usuarios/BorrarUsuario.xhtml");
					add("/gestorEscolar/view/usuarios/EditarUsuario.xhtml");
					add("/gestorEscolar/view/usuarios/ListadoUsuarios.xhtml");
				}
			});
			put("profesor", new HashSet<String>() {
				{
					add("/gestorEscolar/access/login.xhtml");
					add("/gestorEscolar/view/asignaturas/altaAsignatura.xhtml");
					add("/gestorEscolar/view/asignaturas/EditarAsignatura.xhtml");
					add("/gestorEscolar/view/asignaturas/ListadoAsignaturas.xhtml");
					add("/gestorEscolar/view/management/profesorIndex.xhtml");
					add("/gestorEscolar/view/navigation/menuBar.xhtml");
				}
			});
		}
	};

	public FacesContext getFacesContext(final ServletRequest request,
			final ServletResponse response) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		if (facesContext != null) {
			return facesContext;
		}

		FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder
				.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
		LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
				.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
		Lifecycle lifecycle = lifecycleFactory
				.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

		ServletContext servletContext = ((HttpServletRequest) request)
				.getSession().getServletContext();
		facesContext = contextFactory.getFacesContext(servletContext, request,
				response, lifecycle);
		InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
		if (null == facesContext.getViewRoot()) {
			facesContext.setViewRoot(new UIViewRoot());
		}

		return facesContext;
	}

	private abstract static class InnerFacesContext extends FacesContext {
		protected static void setFacesContextAsCurrentInstance(
				final FacesContext facesContext) {
			FacesContext.setCurrentInstance(facesContext);
		}
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String uri = request.getRequestURI();

		// Ignore JSF2/RF4 resources (which are also mapped on FacesServlet).
		if (uri.startsWith(ResourceHandler.RESOURCE_IDENTIFIER)
				|| uri.startsWith(ResourceHandlerImpl.RICHFACES_RESOURCE_IDENTIFIER)) {
			chain.doFilter(request, response);
			return;
		}

		FacesContext facesContext = getFacesContext(request, response);
		if (facesContext != null
				&& !uri.equals("/gestorEscolar/access/login.xhtml")) {
			LoginBean login = (LoginBean) FacesContext.getCurrentInstance()
					.getExternalContext().getSessionMap().get("loginBean");

			if (login != null) {

				UsuarioView usuario = login.getUsuario();

				if (usuario != null && usuario.getRol() != null) {
					HashSet<String> pagesAuthorized = mapaPermisos.get(usuario
							.getRol());
					if (pagesAuthorized != null
							&& pagesAuthorized.contains(uri)) {
						chain.doFilter(request, response);
						return;
					}
				}
			}

			response.sendRedirect("/gestorEscolar/access/login.xhtml");
			return;
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
}
